package com.example.demo.leetcode.classics150;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _49合并区间
 * @description
 * @date 2023/07/24 17:07
 * <p>
 * ******************************************************
 */
public class _49合并区间 {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> {
            if (a[0] == b[0]) {
                return b[1] - a[1];
            }
            return a[0] - b[0];
        });

        LinkedList<LinkedList<Integer>> res = new LinkedList<>();


        for (int i = 0; i < intervals.length; i++) {
            int[] interval = intervals[i];
            if (i == 0) {
                LinkedList<Integer> first = new LinkedList<>();
                first.addLast(interval[0]);
                first.addLast(interval[1]);
                res.addLast(first);
            } else {
                LinkedList<Integer> last = res.getLast();
                if (interval[0] > last.getLast()) {
                    LinkedList<Integer> item = new LinkedList<>();
                    item.addLast(interval[0]);
                    item.addLast(interval[1]);
                    res.addLast(item);
                } else {
                    if (interval[1] > last.getLast()) {
                        last.removeLast();
                        last.addLast(interval[1]);
                    }
                }
            }
        }


        int[][] result = new int[res.size()][2];
        for (int i = 0; i < res.size(); i++) {
            LinkedList<Integer> curr = res.get(i);
            result[i] = curr.stream().mapToInt(Integer::intValue).toArray();
        }
        return result;
    }
}
